package cn.jasonone.views;

import cn.jasonone.model.QRCodeModel;
import com.alibaba.excel.EasyExcel;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.aztec.AztecWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.*;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileReader;
import java.net.URLEncoder;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Map;
import java.util.Objects;

/**
 * Excel视图处理器
 *
 * @author xujie
 * @version 1.0.0
 */
public class QRCodeView extends AbstractUrlBasedView {
    private final String absolutePath;

    public QRCodeView(String absolutePath) {
        this.absolutePath = absolutePath;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/png");
        //生成二维码类

        String content = Objects.toString(model.get("content"), "");
        Gson gson = new Gson();
        QRCodeModel codeModel = gson.fromJson(new FileReader(this.absolutePath), QRCodeModel.class);
        Writer qrCodeWriter = getWriter(codeModel.getFormat());
        //生成的二维码
        BitMatrix bitMatrix = qrCodeWriter.encode(content, codeModel.getFormat(), codeModel.getWidth(), codeModel.getHeight(), codeModel.getHints());
        //输出二维码图片
        MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());
    }

    public Writer getWriter(BarcodeFormat format) {
        switch (format) {
            case CODE_93:
                return new Code93Writer();
            case CODE_39:
                return new Code39Writer();
            case ITF:
                return new ITFWriter();
            case AZTEC:
                return new AztecWriter();
            case CODE_128:
                return new Code128Writer();
            case EAN_8:
                return new EAN8Writer();
            case EAN_13:
                return new EAN13Writer();
            default:
                return new QRCodeWriter();
        }
    }
}
